package com.edou.system.listener;

import javax.annotation.Resource;
import javax.servlet.ServletContext;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.simple.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import com.edou.system.entity.SysUploadSet;
import com.edou.system.service.ISysRegionService;
import com.edou.system.service.ISysUploadSetService;

/**
 * SYSTEM模块初始化操作
 * @creator     admin
 * @create-time Jun 21, 2012   4:44:43 PM
 * @version 0.1
 */
@Component
public class SystemInitDataListener implements ApplicationListener<ContextRefreshedEvent> {

	private Log log = LogFactory.getLog(SystemInitDataListener.class);
	
	@Autowired(required = false)
	private ServletContext servletContent;
	
	@Resource(name = "sysUploadSetServiceImpl")
	private ISysUploadSetService sysUploadSetService;
	@Value("${upload.type:local}")
	private String uploadType;
	@Value("${aliyun.oss.endpoint:{NULL}}")
	private String endpoint;
	@Value("${aliyun.oss.bucketname.publicforread:{NULL}}")
	private String bucketNameForPublicRead;
	@Resource(name = "sysRegionServiceImpl")
	private ISysRegionService sysRegionService;
	
	
	public void onApplicationEvent(ContextRefreshedEvent event) {
		log.info("====== SYSTEM模块数据初始化开始======");
		
		if(null != servletContent){
			//加载上传配置表数据
			SysUploadSet sysUploadSet = sysUploadSetService.getSysUploadSet();
			servletContent.setAttribute("sysUploadSet", sysUploadSet);
			servletContent.setAttribute("fileRoot", sysUploadSet.getPublicRoot());
			servletContent.setAttribute("uploadType", uploadType);
			
			if(StringUtils.equals(uploadType, "oss")){
				//加载阿里云OSS数据
				int split = endpoint.indexOf("//");
				String start = endpoint.substring(0,split+2);
				String end = endpoint.substring(split+2);
				String aliyunOssFileAccessUrl = start + bucketNameForPublicRead + "." + end + "/";
				
				servletContent.setAttribute("aliyunOssFileAccessUrl", aliyunOssFileAccessUrl);
			}
			//查询省市区数据
			JSONObject regionJSON = sysRegionService.getRegionJSON();
			servletContent.setAttribute("regionJSON", regionJSON);
		}
		log.info("====== SYSTEM模块数据初始化完毕 ======");
	}

}
